package com.fast.framework.config.security.customize;

import cn.hutool.core.util.StrUtil;
import com.fast.framework.constant.HttpStatus;
import com.fast.framework.utils.ServletUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 当访问接口没有权限时。引用的位置：SecurityConfig文件里的 `configure(HttpSecurity http)-> http.exceptionHandling()`
 * </p>
 *
 * @author lanyuankeji
 */
@Component("accessDeniedHandler")
public class AccessDeniedHandler implements org.springframework.security.web.access.AccessDeniedHandler {
    /**
     * 处理访问被拒绝的情况
     *
     * @param request               HTTP 请求对象
     * @param response              HTTP 响应对象
     * @param accessDeniedException 访问被拒绝异常
     * @throws IOException      IO 异常
     * @throws ServletException Servlet 异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String msg = StrUtil.format("请求访问：{}，权限不足，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderObject(response, HttpStatus.UNAUTHORIZED, msg);
    }
}
